package com.weichen.xd;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.weichen.xd.data.DailyForecast;
import com.weichen.xd.utils.CPResourceUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Dune on 2017/9/11.
 */

public class DateWeatherAdapter extends RecyclerView.Adapter<DateWeatherAdapter.ViewHolder> {

    private List<DailyForecast> mDailyForecast;

    public void setDailyForecast(List<DailyForecast> dailyForecast) {
        this.mDailyForecast = dailyForecast;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_date_weather, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        DailyForecast dailyForecast = mDailyForecast.get(position);

        holder.tvTemRange.setText(holder.tvTemRange.getContext().getString(R.string.format_item_tmp_max_min,
                dailyForecast.getTmp().getMin(), dailyForecast.getTmp().getMax()));
        holder.ivItemTmpIc.setImageResource(CPResourceUtil.getDrawableId(holder.ivItemTmpIc.getContext()
                , "ic_code_" + dailyForecast.getCond().getCodeD()));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        try {
            Date date = sdf.parse(dailyForecast.getDate());
            holder.tvWeek.setText(getWeekOfDate(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    @Override
    public int getItemCount() {
        return mDailyForecast == null ? 0 : mDailyForecast.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_week)
        TextView tvWeek;
        @BindView(R.id.tv_tem_range)
        TextView tvTemRange;
        @BindView(R.id.iv_item_tmp_ic)
        ImageView ivItemTmpIc;

        public ViewHolder(View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);
        }
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
}
